<template>
  <el-form :inline="true" :model="formData" class="demo-form-inline">
    <el-form-item label="往来单位：">
      <el-select v-model="formData.erpSupplier.supId" clearable style="width: 280px; margin-left: 10px;"
        placeholder="请选择往来单位">
        <el-option v-for="customer in customers" :key="customer.id"
          :label="`${customer.supName} ${customer.supType === '0' ? '[供应商]' : '[客户]'}`" :value="customer.supId" />
      </el-select>
    </el-form-item>

    <el-form-item label="单据编号">
      <el-input v-model="formData.billNo" placeholder="自动生成单据编号" readonly></el-input>
    </el-form-item>

    <el-form-item label="创建时间">
      <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>

    <el-form-item label="财务人员：">
      <el-select v-model="formData.erpPerson.perId" clearable style="width: 200px; margin-left: 10px;" placeholder="请选择财务人员">
  <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName" :value="persons.perId" />
  <el-option :value="undefined" disabled style="cursor: pointer">
    <el-button type="text" v-perm:finance:revenue:insert:financestaff="insert">
      <i class="el-icon-menu"></i>新增财务人员
    </el-button>
  </el-option>
</el-select>

    </el-form-item>

    <el-table :data="tableData" show-summary style="width: 100%">
      <el-table-column v-if="showIdColumn" label="id" width="400">
                <template #default="{ row }">
                    <el-input v-model="row.id"></el-input>
                </template>
            </el-table-column>
      <el-table-column label="支出项目" width="400">
        <template #default="{ row }">
          <el-select v-model="row.xm" clearable style="width: 293px; margin-left: 10px;" placeholder="请选择支出项目">
            <el-option v-for="status in stausData" :key="status.itemId" :label="status.name" :value="status.itemId" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="金额" width="400">
        <template #default="{ row }">
          <el-input v-model="row.je"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="400">
        <template #default="{ row }">
          <el-input v-model="row.bz"></el-input>
        </template>
      </el-table-column>
    </el-table>

    <div class="index-body zb">
      <el-form-item label="支出账户：" style="margin-right: 120px;">
        <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="formData.erpAccount.accId">
          <el-option v-for="account in accounts" :key="account.id" :label="account.name" :value="account.accId" />
        </el-select>
      </el-form-item>

      <el-form-item label="支出金额：" style="margin-right: 100px;">
        <el-input style="width: 240px" v-model="formData.totalPrice" placeholder="请输入支出金额"></el-input>
      </el-form-item>
    </div>

    <div class="ant-coloery" style="margin-right: 10px;">
      <el-form-item label="附件：">
        <el-button plain>
          <el-icon style="margin-right: 10px;">
            <MessageBox />
          </el-icon>上传附件
        </el-button>
      </el-form-item>
    </div>
  </el-form>

  <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="40%"
    style="margin-left: 550px; margin-top: 200px">
    <router-view @close="close" :data="data"></router-view>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, defineProps, defineEmits } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';

// 变量定义
const visible = ref(false);
const title = ref("");

const ruleForm = ref({
  linkNumber: '',
  number: '',
  organId: '',
  accountId: '',
  handsPersonId: '',
});

let props = defineProps(["data"]);
let emits = defineEmits(["close"]);
let formData = ref({ ...props.data });

const tableData = ref([]); // 表格数据初始化

// 关闭对话框的函数
const close = () => {
  visible.value = false;
};

// 页面加载时将 formData 中的数据赋值给 tableData
onMounted(() => {
  if (formData.value.erpAccountItems && Array.isArray(formData.value.erpAccountItems)) {
    tableData.value = formData.value.erpAccountItems.map(item => ({
      id: item.id,

      xm: item.erpInOutItem.itemId, // 使用传入的 itemId
      je: item.eachAmount || 0,
      bz: item.remark || ''
    }));
  }
});


// 向表格添加新行的函数
const addRow = () => {
  tableData.value.push({
    xm: '',
    je: 0,
    bz: '',
  });
};
const person = ref({})
const personfin = () => {
  request({
    url: '/basic/person/list',
    method: 'get'

  }).then(res => {
    person.value = res.data
    console.log(res)
  })
}

personfin();
// 从 API 加载客户数据
const customers = ref([]);
const loadCustomers = () => {
  request({ url: '/basic/vendor/findBy', method: 'get' })
    .then(res => {
      console.log(res);
      customers.value = res.data; // 更新客户数据
    }).catch(err => {
      console.error(err);
    });
};
loadCustomers();

const accounts = ref([]);
const loadAccounts = () => {
  request({ url: '/basic/account/list', method: 'get' })
    .then(res => accounts.value = res.data)
    .catch(err => console.error(err));
};
loadAccounts();

// 提交表单
const submitForm = () => {
  const totalAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);

  const data = {
    erpAccountHead: {
      billNo: formData.value.billNo,
      organId: formData.value.erpSupplier.supId,
      creator: '1',
      accountId: formData.value.erpAccount.accId,
      handsPersonId: formData.value.handsPersonId,
      changeAmount: totalAmount,
      totalPrice: totalAmount,
      status: '0'
    },
    erpAccountItems: tableData.value.map(row => ({
      id: row.id ,
      inOutItemId: row.xm,
      remark: row.bz || '',
      eachAmount: row.je,
    })),
  };


  request({
    url: '/accountHead/update',
    method: 'put',
    params: { billNo: formData.value.billNo },
    data: data,
    headers: { 'Content-Type': 'application/json' },
  }).then(res => {
    console.log(res);
    ElMessage.success('提交成功');
  }).catch(err => {
    console.error(err);
    ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
  });
};

// 其他相关函数...
const stausData = [
  { itemId: 1, name: '利息收入' },
  { itemId: 2, name: '房租收入' }
];


</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
